<?php

namespace app\controller;

use app\BaseController;
use app\model\User;
use think\facade\Cache;
use think\facade\Filesystem;

class Index extends BaseController
{
    public function index()
    {
        return View('index');
    }

    public function upload()
    {
        $file= request()->file('file');
        $saveName = Filesystem::disk('upload')->putFile('',$file,'md5');
        $saveName = str_replace('\\', '', '/uploads/' . $saveName);
        $data = [
            'image' => $saveName,
        ];
        return json_encode($data);
    }

    public function login()
    {
        if(request()->isPost()){
            $nickname = request()->post('nickname');
            $avatar = request()->post('avatar');

            // 设置默认头像
            if(!$avatar){
                $avatar = '/static/image/default.jpg';
            }

            $token = md5($nickname);
            $data = [
                'token' => md5($nickname),
                'nickname' => $nickname,
                'avatar' => $avatar,
                'create_time' => time(),
            ];
            // 更新用户信息
            Cache::store('redis')->set('users'.$token,$data);
            // 写入数据库
            $userWhere = [
                'token' => $token,
            ];
            $userInfo = User::where($userWhere)->find();
            if(!$userInfo){
                User::insert($data);
            }
            return json_encode($data);
        }else{
            return View('login');
        }
    }

    // 退出
    public function logout()
    {
        $token = request()->post('token');
        $userInfo = Cache::store('redis')->get('users'.$token);
        Cache::store('redis')->del('online_user'.$userInfo['fd']);
        Cache::store('redis')->del('users'.$token);
        $data = [
            'status' => 1,
        ];
        return json_encode($data);
    }

}
